﻿using Unity.Burst;
using Unity.Mathematics;

namespace Game.FlowField.Burst
{
    [BurstCompile]
    public struct Position2IndexHelper
    {
        private int2 m_MapSize;
        private float2 m_GridSize;

        public Position2IndexHelper(int2 mapSize, float2 gridSize)
        {
            this.m_MapSize = mapSize;
            this.m_GridSize = gridSize;
        }

        [BurstCompile]
        public bool TryGetIndex2D(float2 position, out int2 result)
        {
            float2 mapPositionMin = -this.m_MapSize * this.m_GridSize * 0.5f;
            var dir = position - mapPositionMin;
            result = (int2)math.ceil(dir / this.m_GridSize) + new int2(-1, -1);
            return result.x >= 0 && 
                   result.y >= 0 && 
                   result.x < this.m_MapSize.x && 
                   result.y < this.m_MapSize.y;
        }

        [BurstCompile]
        public bool TryGetIndex(float2 position, out int result)
        {
            float2 mapPositionMin = -this.m_MapSize * this.m_GridSize * 0.5f;
            var dir = position - mapPositionMin;
            var index2d= (int2)math.ceil(dir / this.m_GridSize) + new int2(-1, -1);
            result = MapDataUtil.ConvertIndex2D2Index(index2d, this.m_MapSize);
            return index2d.x >= 0 &&
                   index2d.y >= 0 &&
                   index2d.x < this.m_MapSize.x &&
                   index2d.y < this.m_MapSize.y;
        }

        [BurstCompile]
        public bool TryGetIndexes(float2 position, out int index, out int2 index2D)
        {
            float2 mapPositionMin = -this.m_MapSize * this.m_GridSize * 0.5f;
            var dir = position - mapPositionMin;
            index2D = (int2)math.ceil(dir / this.m_GridSize) + new int2(-1, -1);
            index = MapDataUtil.ConvertIndex2D2Index(index2D, this.m_MapSize);
            return index2D.x >= 0 &&
                   index2D.y >= 0 &&
                   index2D.x < this.m_MapSize.x &&
                   index2D.y < this.m_MapSize.y;
        }
    }
}